﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using Domain.Model;

namespace Web.Filters
{
    /// <summary>
    /// 登录制授权控制特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class LoginAttribute : FilterAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="filterContext">权限上下文</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var user = filterContext.HttpContext.Session["LoginUser"] as User;
            var controller = filterContext.Controller as BasicController;
            if (controller != null)
            {
                if (user != null)
                {
                    controller.SetLoginUser(user);
                }
                else
                {
                    this.Redirect(filterContext);
                }
            }
        }

        /// <summary>
        /// 跳转到指定页面
        /// </summary>
        /// <param name="context">上下文</param> 
        private void Redirect(AuthorizationContext context)
        {

            if (context.RouteData.DataTokens["area"] == null)
            {
                context.Result = new RedirectResult("system");
            }
            else
            {
                var loginUrl = ("/" + context.RouteData.DataTokens["area"].ToString()).ToLower();
                if (context.HttpContext.Request.IsAjaxRequest())
                {
                    context.Result = new HttpUnauthorizedResult(loginUrl); // ajax 401
                }
                else
                {
                    context.Result = new RedirectResult(loginUrl);
                }
            }
        }
    }
}

